package com.neusoft.neuiotms.dcom.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.bizcore.web.utils.id.BaseIdGenerator;
import com.neusoft.neuiotms.dcom.dto.OperationGroupDTO;
import com.neusoft.neuiotms.dcom.model.OperationGroup;
import com.neusoft.neuiotms.dcom.repository.InstitutionsRepository;
import com.neusoft.neuiotms.dcom.repository.OperationGroupRepository;

@Component
public class OperationGroupConverter extends AbstractConverter<OperationGroup, OperationGroupDTO> {

    @Autowired
    private OperationGroupRepository operationGroupRepository;
    @Autowired
    private BaseIdGenerator operationGroupCodeGenerator;
    @Autowired
    private InstitutionsRepository institutionsRepository;
    @Autowired
    private InstitutionsConverter institutionsConverter;

    @Override
    public OperationGroup toModel(final OperationGroupDTO dto) {

        OperationGroup model;
        if (dto.isNew()) {
            model = new OperationGroup();
            model.setCode(this.operationGroupCodeGenerator.generateCode());
        } else {
            model = this.operationGroupRepository.getOne(dto.getId());
            model.setCode(dto.getCode());
        }

        model.setName(dto.getName());
        model.setGroupLeaderCode(dto.getGroupLeaderCode());
        model.setGroupLeaderName(dto.getGroupLeaderName());

        model.getInstitutions().clear();
        if (null != dto.getInstitutions()) {
            dto.getInstitutions().stream().map(k -> this.institutionsRepository.findByCode(k)).filter(s -> null != s)
                    .forEach(model.getInstitutions()::add);
        }

        return model;
    }

    @Override
    public OperationGroupDTO toDTO(final OperationGroup model, final boolean forListView) {

        final OperationGroupDTO dto = new OperationGroupDTO();

        dto.setId(model.getId());
        dto.setCode(model.getCode());
        dto.setName(model.getName());
        dto.setGroupLeaderCode(model.getGroupLeaderCode());
        dto.setGroupLeaderName(model.getGroupLeaderName());

        if (null != model.getInstitutions()) {

            model.getInstitutions().stream().map(k -> this.institutionsConverter.toDTO(k))
                    .forEach(dto.getInstitutionsList()::add);
        }
        return dto;
    }

}
